package com.cskaoyan.service.goods;

import com.cskaoyan.mapper.*;
import com.cskaoyan.model.bean.*;
import com.cskaoyan.model.bean.Comment;
import com.cskaoyan.model.bo.goods.CommentBo;
import com.cskaoyan.model.vo.goods.wxVo.*;
import com.github.pagehelper.PageHelper;
import com.sun.org.apache.xerces.internal.impl.dv.xs.TimeDV;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class WxGoodsServiceIml implements WxGoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    CollectMapper collectMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Autowired
    TopicMapper topicMapper;

    @Autowired
    FootprintMapper footprintMapper;

    @Autowired
    RegionMapper regionMapper;

    @Override
    public int goodsCount() {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andDeletedEqualTo(false);
        return (int)goodsMapper.countByExample(goodsExample);
    }

    @Override                     // 此id 是父目录的id 通过id 查pi
    public CategoryVo goodsListByCatgory(Integer id) {
        CategoryExample parentCatExample = new CategoryExample();
        parentCatExample.createCriteria().andPidEqualTo(0);
        List<Integer> parentIds = new ArrayList<>();
        List<Category> parentscategories = categoryMapper.selectByExample(parentCatExample);
        for (Category parentcat : parentscategories) {
            parentIds.add(parentcat.getId());
        }

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andPidEqualTo(id);
        List<Category> brotherCategory = categoryMapper.selectByExample(categoryExample);


        if (parentIds.contains(id)) {

            Category currentCategory = brotherCategory.get(0);//  TODO tes一下
            Category parentCategory = categoryMapper.selectByPrimaryKey(id);
            //TODO return
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setCurrentCategory(currentCategory);
            categoryVo.setBrotherCategory(brotherCategory);
            categoryVo.setParentCategor(parentCategory);
            return categoryVo;
        }

        Category childCate = categoryMapper.selectByPrimaryKey(id);
        Integer pId = childCate.getPid();//
        Category CurCategory = categoryMapper.selectByPrimaryKey(id);
        Category pCategory = categoryMapper.selectByPrimaryKey(pId);
        // TODO return
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setCurrentCategory(CurCategory);
        categoryVo.setBrotherCategory(brotherCategory);
        categoryVo.setParentCategor(pCategory);


        return categoryVo;
    }

    @Override          //xianshi goods
    public GoodsListVo goodsLists(Integer categoryId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(categoryId).andDeletedEqualTo(false);

        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        List<GoodsVo> goodsVos = new ArrayList<>();

        for (Goods goods : goodsList) {
            GoodsVo goodsVo = new GoodsVo();

            goodsVo.setId(goods.getId());
            goodsVo.setName(goods.getName());
            goodsVo.setBrief(goods.getBrief());
            goodsVo.setPicUrl(goods.getPicUrl());
            goodsVo.setIsNew(goods.getIsNew());
            goodsVo.setIsHot(goods.getIsHot());
            goodsVo.setCounterPrice(goods.getCounterPrice());
            goodsVo.setRetailPrice(goods.getRetailPrice());

            goodsVos.add(goodsVo);
        }

        GoodsListVo goodsListVo = new GoodsListVo();
        goodsListVo.setGoodsList(goodsVos);
        goodsListVo.setCount(goodsList.size());

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andIdBetween(1005007, 1008001);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        goodsListVo.setFilterCategoryList(categories);

        return goodsListVo; // 测试
    }


    public GoodsDetailVo goodsDetail(Integer id) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userId = userMapper.selectIdByUsername(username);

        FootprintExample footprintExample = new FootprintExample();
        footprintExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(id);
        List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
        Footprint footprint = new Footprint();
        if (footprints.size() == 0) {

            footprint.setUserId(userId);
            footprint.setGoodsId(id);
            footprint.setAddTime(new Date());
            footprint.setUpdateTime(new Date());
            footprint.setDeleted(false);
            footprintMapper.insertSelective(footprint);
        } else {
            footprint = footprints.get(0);
            footprint.setUpdateTime(new Date());
            footprintMapper.updateByPrimaryKey(footprint);
        }


        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsSpecification> specifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        Set<String> set = new HashSet<>();
        for (GoodsSpecification s : specifications) {
            set.add(s.getSpecification());
        }
        List<SpecificatonVo> specificatonVos = new ArrayList<>();//////
        for (String name : set) {
            SpecificatonVo specificatonVo = new SpecificatonVo();

            specificatonVo.setName(name);
            specificatonVo.setValueList(new ArrayList<GoodsSpecification>());////// TODO
            specificatonVos.add(specificatonVo);
        }

        for (GoodsSpecification s : specifications) {
            for (SpecificatonVo spec : specificatonVos) {
                if (s.getSpecification().equals(spec.getName())) {

                    spec.getValueList().add(s);
                    break;
                }
            }
        }


        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setSpecificationList(specificatonVos);


        //group 不要
        goodsDetailVo.setGroupon(new Integer[]{});

        IssueExample issueExample = new IssueExample();
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        goodsDetailVo.setIssue(issues);   //

        CollectExample collectExample = new CollectExample();
        collectExample.createCriteria().andTypeEqualTo((byte) 0).andValueIdEqualTo(id).andUserIdEqualTo(userId);
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        if (collects.size() > 0) {
            goodsDetailVo.setUserHasCollect(1); //      TODO 需获得用户Id
        }
        goodsDetailVo.setUserHasCollect(0);

        goodsDetailVo.setShareImage(" ");//  TODO


        CommentExample commentExample = new CommentExample();

        commentExample.createCriteria().andValueIdEqualTo(id).andTypeEqualTo(new Byte((byte)0));

        List<Comment> comments = new ArrayList<>();
        comments = commentMapper.selectByExample(commentExample);


        List<WxComment> dataList = new ArrayList<>();
        if (comments.size() != 0) {
            for (Comment c : comments.subList(0,6)) {
                WxComment wxComment = new WxComment();
                wxComment.setAddTime(c.getAddTime());


            if (c.getHasPicture() == true) {
                wxComment.setPicList(c.getPicUrls());
            }



                Integer uId = c.getUserId();

                wxComment.setNickname(userMapper.selectByPrimaryKey(uId).getNickname());
                wxComment.setId(c.getId());
                wxComment.setAvatar(userMapper.selectByPrimaryKey(uId).getAvatar());
                wxComment.setContent(c.getContent());

                dataList.add(wxComment);


            }
        }



        CommentVo commentVo = new CommentVo();
        commentVo.setData(dataList);
        commentVo.setCount(comments.size());


        goodsDetailVo.setComment(commentVo);


        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        goodsDetailVo.setAttribute(goodsAttributes);


        Goods goods = goodsMapper.selectByPrimaryKey(id);
        Integer brandId = goods.getBrandId();
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        goodsDetailVo.setBrand(brand);


        goodsDetailVo.setInfo(goods);

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        goodsDetailVo.setProductList(goodsProducts);//


        return goodsDetailVo;
    }

    //===================================================

   /* @Override
    public RelateGoodsVo goodsRelated(Integer id) {

        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdBetween(id-20,id+20);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        ArrayList<GoodsVo> goodsList = new ArrayList<>();
        for (Goods g:goods) {
            GoodsVo relate = new GoodsVo();
            relate.setId(g.getId());
            relate.setName(g.getName());
            relate.setPicUrl(g.getPicUrl());
            relate.setIsNew(g.getIsNew());
            relate.setIsHot(g.getIsHot());
            relate.setCounterPrice(g.getCounterPrice());
            relate.setRetailPrice(g.getRetailPrice());

            goodsList.add(relate);
        }

        RelateGoodsVo relateGoodsVo = new RelateGoodsVo();
        relateGoodsVo.setGoodsList(goodsList);

        return relateGoodsVo;
    }*/
//===================================================================


    @Override
    public TopicDetalVo topicDetail(Integer id) {
        TopicDetalVo topicDetalVo = new TopicDetalVo();

        Topic topic = topicMapper.selectByPrimaryKey(id);
//        String[] goodsIds = topic.getGoods();
//        List<Integer> integers = new ArrayList<>();
//        for (String goods : goodsIds) {
//            integers.add(Integer.parseInt(goods));
//        }
//        GoodsExample goodsExample = new GoodsExample();
//        goodsExample.createCriteria().andIdIn(integers);
//        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        topicDetalVo.setTopic(topic);
//        topicDetalVo.setGoods(goodsList);
        return topicDetalVo;
    }

    @Override
    public List<Topic> topicRealted(Integer id) {
        TopicExample topicExample = new TopicExample();
        topicExample.createCriteria().andIdBetween(id - 10, id + 10);
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);

        return topics;
    }

    @Override
    public CountCommentVo commentCount(Integer valueId, Byte type) {
        CountCommentVo countCommentVo = new CountCommentVo();

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andTypeEqualTo(type).andValueIdEqualTo(valueId).andDeletedEqualTo(false);
        long count = commentMapper.countByExample(commentExample);

        CommentExample commentExampPic = new CommentExample();
        commentExampPic.createCriteria().andTypeEqualTo(type).andValueIdEqualTo(valueId).andHasPictureEqualTo(true);
        long picCount = commentMapper.countByExample(commentExampPic);
        countCommentVo.setAllCount((int) count);
        countCommentVo.setHasPicCount((int) picCount);                          //test
        return countCommentVo;

    }

    @Override
    public CommentListVo comentLists(Integer valueId, Byte type, Integer size, Integer page, Byte showType) {

        PageHelper.startPage(page, size);    // TODO 分页


        List<CommentListDataVo> commentListDataVos = new ArrayList<>();

        if (showType == 0) {

            CommentExample commentExample = new CommentExample();
            commentExample.createCriteria().andTypeEqualTo(type).andValueIdEqualTo(valueId).andDeletedEqualTo(false);
            List<Comment> comments = commentMapper.selectByExample(commentExample);

            for (Comment c : comments) {
                CommentListDataVo commentListDataVo = new CommentListDataVo();

                CommentUserVo commentUserVo = new CommentUserVo();
                User user = userMapper.selectByPrimaryKey(c.getUserId());
                commentUserVo.setNickName(user.getNickname());
                commentUserVo.setAvatarUrl(user.getAvatar());

                commentListDataVo.setUserInfo(commentUserVo);
                commentListDataVo.setAddTime(c.getAddTime());
                commentListDataVo.setPicList( c.getPicUrls());      ///
                commentListDataVo.setContent(c.getContent());
                commentListDataVos.add(commentListDataVo);
            }
        } else {
            CommentExample commentExamplePic = new CommentExample();
            commentExamplePic.createCriteria().andValueIdEqualTo(valueId).andTypeEqualTo(type).andHasPictureEqualTo(true);
            List<Comment> comments = commentMapper.selectByExample(commentExamplePic);
            for (Comment c : comments) {
                CommentListDataVo commentListDataVo = new CommentListDataVo();

                CommentUserVo commentUserVo = new CommentUserVo();
                User user = userMapper.selectByPrimaryKey(c.getUserId());
                commentUserVo.setNickName(user.getNickname());
                commentUserVo.setAvatarUrl(user.getAvatar());

                commentListDataVo.setUserInfo(commentUserVo);
                commentListDataVo.setAddTime(c.getAddTime());
                commentListDataVo.setPicList(c.getPicUrls());
                commentListDataVo.setContent(c.getContent());
                commentListDataVos.add(commentListDataVo);
            }

        }


        CommentListVo commentListVo = new CommentListVo();
        commentListVo.setData(commentListDataVos);
        commentListVo.setCount(commentListDataVos.size());
        commentListVo.setCurrentPage(page);


        return commentListVo;

    }

    @Override
    public  TopicListsVo topicLists(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        TopicExample topicExample = new TopicExample();

        List<Topic> topics = topicMapper.selectByExample(topicExample);
        List<TopicL> topicLS = new ArrayList<>();
        for (Topic t : topics) {
            TopicL topicL = new TopicL();
            topicL.setId(t.getId());
            topicL.setTitle(t.getTitle());
            topicL.setSubtitle(t.getSubtitle());
            topicL.setPrice(t.getPrice());
            topicL.setReadCount(t.getReadCount());
            topicL.setPicUrl(t.getPicUrl());
            topicLS.add(topicL);
        }

        TopicListsVo topicListsVo = new TopicListsVo();
        topicListsVo.setData(topicLS);
        topicListsVo.setCount((int)topicMapper.countByExample(topicExample));

        return topicListsVo;




    }

    @Override
    public List<Region> regionLists(Integer pid) {
        RegionExample regionExample = new RegionExample();
        regionExample.createCriteria().andPidEqualTo(pid);
        List<Region> regions = regionMapper.selectByExample(regionExample);
        return regions;
    }

    @Override
    public Comment commentAdd(CommentBo commentBo) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userId = userMapper.selectIdByUsername(username);

        Comment comment = new Comment();
        comment.setType(commentBo.getType());
        comment.setValueId(commentBo.getValueId());
        comment.setContent(commentBo.getContent());
        comment.setStar(commentBo.getStar());
        comment.setHasPicture(commentBo.getHasPicture());
        comment.setPicUrls(Arrays.asList(commentBo.getPicUrls()));
        comment.setUserId(userId);
        comment.setAddTime(new Date());
        comment.setUpdateTime(new Date());

        commentMapper.insertSelective(comment);

        return comment;
    }

    @Override
    public RelateGoodsVo goodsRelated(Integer id) {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdBetween(id - 10, id + 10);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

       List<GoodsVo> goodsVos = new ArrayList<>();
        for (Goods g : goods) {
            GoodsVo goodsVo = new GoodsVo();
            goodsVo.setId(g.getId());
            goodsVo.setName(g.getName());
            goodsVo.setBrief(g.getBrief());
            goodsVo.setPicUrl(g.getPicUrl());
            goodsVo.setIsNew(g.getIsNew());
            goodsVo.setIsHot(g.getIsHot());
            goodsVo.setCounterPrice(g.getCounterPrice());
            goodsVo.setRetailPrice(g.getRetailPrice());
            goodsVos.add(goodsVo);
        }

        RelateGoodsVo relateGoodsVo = new RelateGoodsVo();
        relateGoodsVo.setGoodsList(goodsVos);
        return relateGoodsVo;

    }
}
